package models

import (
	"errors"

	"golang.org/x/crypto/bcrypt"

	orm "go-papers/database"
	"go-papers/tools"
)

// User
type User struct {
	// key
	IdentityKey string
	// 用户名
	UserName  string
	FirstName string
	LastName  string
	// 角色
	Role string
}

type UserName struct {
	Username string `gorm:"type:varchar(64)" json:"username"`
}

type PassWord struct {
	// 密码
	Password string `gorm:"type:varchar(128)" json:"password"`
}

type LoginM struct {
	UserName
	PassWord
}

type SysUserId struct {
	UserId int `gorm:"primary_key;AUTO_INCREMENT"  json:"userId"` // 编码
}

type SysUserB struct {
	NickName     string `gorm:"type:varchar(128)" json:"nickName"`  // 昵称
	Phone        string `gorm:"type:varchar(11)" json:"phone"`      // 手机号
	RoleId       int    `gorm:"type:int(11)" json:"roleId"`         // 角色编码
	UserMemberId int    `gorm:"type:int(11)" json:"user_member_id"` // 角色编码
	Salt         string `gorm:"type:varchar(255)" json:"salt"`      //盐
	Avatar       string `gorm:"type:varchar(255)" json:"avatar"`    //头像
	Sex          string `gorm:"type:varchar(255)" json:"sex"`       //性别
	Email        string `gorm:"type:varchar(128)" json:"email"`     //邮箱
	UserType     string `gorm:"type:varchar(2)" json:"userType"`    //用户类型 1 平台  2 社区达人  3 机构
	OrganId      int    `gorm:"type:int(11)" json:"organId"`        //所属机构
	OrganName    string `gorm:"type:varchar(255)" json:"organName"` //所属机构
	DeptId       int    `gorm:"type:int(11)" json:"deptId"`         //部门编码
	DeptName     string `gorm:"type:varchar(128)" json:"deptName"`  //部门编码
	PostId       int    `gorm:"type:int(11)" json:"postId"`         //职位编码
	CreateBy     string `gorm:"type:varchar(128)" json:"createBy"`  //
	UpdateBy     string `gorm:"type:varchar(128)" json:"updateBy"`  //
	Remark       string `gorm:"type:varchar(255)" json:"remark"`    //备注
	Status       string `gorm:"type:int(1);" json:"status"`
	DataScope    string `gorm:"-" json:"dataScope"`
	Params       string `gorm:"-" json:"params"`

	BaseModel
}

type SysUser struct {
	SysUserId
	SysUserB
	LoginM
}

func (SysUser) TableName() string {
	return "sys_user"
}

type SysUserPwd struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

type SysUserPage struct {
	SysUserId
	SysUserB
	LoginM
	PostName string `gorm:"-" json:"postName"`
	PostCode string `gorm:"-" json:"postCode"`
}

type SysUserView struct {
	SysUserId
	SysUserB
	LoginM
	RoleName string `gorm:"column:role_name"  json:"role_name"`
}

// 获取用户数据
func (e *SysUser) Get() (SysUserView SysUserView, err error) {

	table := orm.Eloquent.Table(e.TableName()).Select([]string{"sys_user.*", "sys_role.role_name"})
	table = table.Joins("left join sys_role on sys_user.role_id=sys_role.role_id")
	if e.UserId != 0 {
		table = table.Where("user_id = ?", e.UserId)
	}

	if e.Username != "" {
		table = table.Where("username = ?", e.Username)
	}

	if e.Password != "" {
		table = table.Where("password = ?", e.Password)
	}

	if e.RoleId != 0 {
		table = table.Where("role_id = ?", e.RoleId)
	}

	if e.DeptId != 0 {
		table = table.Where("dept_id = ?", e.DeptId)
	}

	if e.PostId != 0 {
		table = table.Where("post_id = ?", e.PostId)
	}

	if err = table.First(&SysUserView).Error; err != nil {
		return
	}
	return
}

func (e *SysUser) GetPostNums(postId int) (int, error) {

	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("post_id = ?", postId)
	var count int
	table.Where("sys_user.deleted_at IS NULL").Count(&count)
	return count, nil
}

func (e *SysUser) GetDeptNums(depId int) (int, error) {

	table := orm.Eloquent.Table(e.TableName())
	table = table.Where("dept_id = ?", depId)
	var count int
	table.Where("sys_user.deleted_at IS NULL").Count(&count)
	return count, nil
}

// GetById
func (e *SysUser) GetById(id int) (SysUserView SysUserView, err error) {

	table := orm.Eloquent.Table(e.TableName()).Select([]string{"sys_user.*", "sys_role.role_name"})
	table = table.Joins("left join sys_role on sys_user.role_id=sys_role.role_id")
	table = table.Where("sys_user.user_id = ?", id)

	if err = table.First(&SysUserView).Error; err != nil {
		return
	}
	return
}

// GetDeptById
func (e *SysUser) GetDeptById(id int) []int {
	var did []int
	var doc SysUser
	_ = orm.Eloquent.Table(e.TableName()).Where("user_id = ? ", id).First(&doc).Error

	if doc.DeptId > 0 {
		//查询 部门下的
		var dept Dept
		dept.DeptId = doc.DeptId
		list, _ := dept.GetList()
		if len(list) > 0 {
			for _, v := range list {
				did = append(did, v.OrganId)
			}
		}
	}

	return did
}

func (e *SysUser) GetUidList(id []int) []SysUserB {
	var doc []SysUserB
	_ = orm.Eloquent.Table(e.TableName()).Where("user_id in (?)", id).Find(&doc).Error
	return doc
}

func (e *SysUser) GetPage(pageSize int, pageIndex int) ([]SysUserPage, int, error) {
	var doc []SysUserPage
	table := orm.Eloquent.Select("sys_user.*,organ.organ_name,sys_dept.dept_name,sys_post.post_name,sys_post.post_code").Table(e.TableName())
	table = table.Joins("inner join sys_dept on sys_dept.dept_id = sys_user.dept_id")
	table = table.Joins("left join sys_post on sys_post.post_id = sys_user.post_id")
	table = table.Joins("left join organ on organ.organ_id = sys_user.organ_id")

	if e.Username != "" {
		table = table.Where("username like ?", "%"+e.Username+"%")
	}
	if e.NickName != "" {
		table = table.Where("nick_name like ?", "%"+e.NickName+"%")
	}
	if e.Status != "" {
		table = table.Where("sys_user.status = ?", e.Status)
	}

	if e.Phone != "" {
		table = table.Where("sys_user.phone like ?", "%"+e.Phone+"%")
	}

	if e.PostId != 0 {
		table = table.Where("sys_user.post_id = ?", e.PostId)
	}
	if e.DeptName != "" {
		table = table.Where("sys_dept.dept_name like ?", "%"+e.DeptName+"%")
	}
	if e.DeptId != 0 {
		//table = table.Where("sys_user.dept_id = ?",e.DeptId)

		table = table.Where("sys_user.dept_id in (select dept_id from sys_dept where dept_path like ? )", "%"+tools.IntToString(e.DeptId)+"%")
	}

	table, _ = HandleOrganCommonTable(table, "sys_dept", e.DataScope, "部门职位列表")

	var count int

	if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Error; err != nil {
		return nil, 0, err
	}
	table.Where("sys_user.deleted_at IS NULL").Count(&count)
	return doc, count, nil
}

//加密
func (e *SysUser) Encrypt() (err error) {
	if e.Password == "" {
		return
	}

	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(e.Password), bcrypt.DefaultCost); err != nil {
		return
	} else {
		e.Password = string(hash)
		return
	}
}

//添加
func (e SysUser) Insert() (id int, err error) {
	if err = e.Encrypt(); err != nil {
		return
	}

	// check 用户名
	var count int
	orm.Eloquent.Table(e.TableName()).Where("username = ?", e.Username).Count(&count)
	if count > 0 {
		err = errors.New("当前" + e.Username + "账户已存在！")
		return
	}

	//添加数据
	if err = orm.Eloquent.Table(e.TableName()).Create(&e).Error; err != nil {
		return
	}
	id = e.UserId
	return
}

//修改
func (e *SysUser) Update(id int) (update SysUser, err error) {
	if err = e.Encrypt(); err != nil {
		return
	}

	if err = orm.Eloquent.Table(e.TableName()).First(&update, id).Error; err != nil {
		return
	}
	if e.RoleId == 0 {
		e.RoleId = update.RoleId
	}

	//参数1:是要修改的数据
	//参数2:是修改的数据
	if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
		return
	}
	return
}

func (e *SysUser) BatchDelete(id []int) (Result bool, err error) {
	if err = orm.Eloquent.Table(e.TableName()).Where("user_id in (?)", id).Delete(&SysUser{}).Error; err != nil {
		return
	}
	Result = true
	return
}

func (e *SysUser) SetPwd(pwd SysUserPwd) (Result bool, err error) {
	user, err := e.Get()
	if err != nil {
		tools.HasError(err, "获取用户数据失败(代码202)", 500)
		Result = false
		return
	}
	_, err = tools.CompareHashAndPassword(user.Password, pwd.OldPassword)
	if err != nil {
		Result = false
		return
	}
	e.Password = pwd.NewPassword
	_, err = e.Update(e.UserId)
	tools.HasError(err, "更新密码失败(代码202)", 500)
	Result = true
	return
}
